package com.sywb.chuangyebao.contract;

import android.text.TextUtils;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.luck.picture.lib.entity.LocalMedia;
import com.sywb.chuangyebao.Constants;
import com.sywb.chuangyebao.R;
import com.sywb.chuangyebao.bean.AppConfig;
import com.sywb.chuangyebao.bean.FileConfigInfo;
import com.sywb.chuangyebao.bean.UploadInfo;
import com.sywb.chuangyebao.utils.HttpCallback;
import com.sywb.chuangyebao.utils.HttpUtils;
import com.sywb.chuangyebao.widget.RichEditor;

import org.bining.footstone.log.Logger;
import org.bining.footstone.mvp.IView;
import org.bining.footstone.presenter.BasePresenter;
import org.bining.footstone.rxjava.luban.Luban;
import org.bining.footstone.rxjava.luban.OnCompressListener;
import org.bining.footstone.rxjava.rxbus.RxBus;
import org.bining.footstone.utils.FileUtils;
import org.bining.footstone.utils.SharedUtils;
import org.bining.footstone.utils.ToastUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by admin on 2018/5/16.
 */

public interface PublishArticleContract {

    interface View extends IView {
        TextView getProgress();
        EditText getEtTitle();
        RichEditor getRichEditor();
        /** 文章id，如果为-1表示新增，否则为修改 */
        int getArticleId();

        /**
         * 调用发布接口成功返回后显示对话框
         * @param type 3审核、1草稿
         */
        void showPublishResultDialog(int type);
    }

    class Presenter extends BasePresenter<View> {
        private List<LocalMedia> mUploadFiles = new ArrayList<>();
        private int mUploadPosition = -1;
        private boolean mIgnoreAppConfigLimit = true; // 忽略图片大小、字数个数限制的逻辑（根据接口配置的大小参数限制）注：IOS没做限制，所以这里设置为true

        @Override
        public void onStart() {

        }

        /**
         * 发布文章
         * @param status 3:提交审核、1:草稿
         */
        public void publish(final int status) {
            String title = mView.getEtTitle().getText().toString().trim();
            String html = mView.getRichEditor().getHtml();
            String text = mView.getRichEditor().getText();
            int articleId = mView.getArticleId();

            Logger.e("调用接口发布：title=" + title + ", html=" + html);
            if(status == 3 && !mIgnoreAppConfigLimit) {
                String appConfigStr = SharedUtils.getString(Constants.APPCONFIG, "");
                if (!TextUtils.isEmpty(appConfigStr)) { // 配置不为空
                    AppConfig appConfig = JSON.parseObject(appConfigStr, AppConfig.class);
                    if(appConfig.getArticleTitleMin() != -1
                            || appConfig.getArticleTitleMax() == -1
                            || appConfig.getArticleContentMin() == -1
                            || appConfig.getArticleTitleMax() == -1) {
                        // 获取不到标题和内容的字数最大最小限制
                        ToastUtils.show(mContext, mContext.getString(R.string.publish_fail));
                        return;

                    } else if(title.length() > appConfig.getArticleTitleMax() || title.length() < appConfig.getArticleTitleMin()) {
                        // 标题字数不在配置范围
                        String msg = mContext.getString(R.string.title_count_range, appConfig.getArticleTitleMin(), appConfig.getArticleTitleMax());
                        ToastUtils.show(mContext, msg);
                        return;

                    } else if(text.length() > appConfig.getArticleContentMax() || text.length() < appConfig.getArticleContentMin()) {
                        // 内容字数不在配置范围
                        String msg = mContext.getString(R.string.content_count_range, appConfig.getArticleContentMin(), appConfig.getArticleContentMax());
                        ToastUtils.show(mContext, msg);
                        return;
                    }

                } else { // 配置为空
                    ToastUtils.show(mContext, mContext.getString(R.string.publish_fail));
                    return;
                }
            }

            mView.showProgress();
            HttpUtils.publishArticle(title, html, status, articleId, new HttpCallback<Object>() {
                @Override
                public void onSuccess(Object o) {
                    RxBus.get().post(Constants.POST_ARTICLE, "");
                    mView.showPublishResultDialog(status);
                }

                @Override
                public void onError(String strMsg) {
                    super.onError(strMsg);
                    showMessage(strMsg);
                }

                @Override
                public void onFinish() {
                    super.onFinish();
                    mView.hideProgress();
                }
            });
        }

        /**
         * 上传图片，上传成功后自动将富文本中的本地图片路径替换成功网络路径
         * @param pics
         */
        public void uploadPicture(List<LocalMedia> pics) {
            mUploadFiles.addAll(pics);
            if(mUploadPosition == -1) {
                uploadFile();
            }
        }

        private synchronized void uploadFile() {
            mUploadPosition++; // 要上传的图片
            if(mUploadPosition >= mUploadFiles.size()) {
                mView.showProgress();
                mUploadPosition = -1;
                mUploadFiles.clear();
                mView.getProgress().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mView.getProgress().setVisibility(android.view.View.GONE);
                    }
                }, 1000);
                return;
            }

            if(mUploadPosition == 0) {
                mView.getProgress().setText(mActivity.getString(R.string.upload_hint, 0, mUploadFiles.size()));
            }

            mView.showProgress();
            mView.getProgress().setVisibility(android.view.View.VISIBLE);
            final LocalMedia localMedia = mUploadFiles.get(mUploadPosition);
            String path = localMedia.getCompressPath();
            Luban.with(mContext).load(path).setCompressListener(new OnCompressListener() { // 压缩处理
                @Override
                public void onStart() {
                    mView.showProgress();
                }

                @Override
                public void onSuccess(List<File> list) { // 压缩成功
                    File file = list.get(0);
                    Logger.e("Luban :" + file.getAbsolutePath());
                    String fileConfig = SharedUtils.getString(Constants.USERFILECONFIG, "");
                    if (!TextUtils.isEmpty(fileConfig) || mIgnoreAppConfigLimit) { // 上传配置不为空
                        FileConfigInfo fileConfigInfo = JSON.parseObject(fileConfig, FileConfigInfo.class);
                        if (fileConfigInfo != null || mIgnoreAppConfigLimit) {
                            try {
                                String fileType = FileUtils.getFileType(file.getAbsolutePath());
                                int fileMaxSize = fileConfigInfo.mime_types.get(fileType).size;
                                if (FileUtils.getFileSize(file) <= fileMaxSize || mIgnoreAppConfigLimit) { // 压缩后的图片小于最大值
                                    HttpUtils.uploadHttp(file, new HttpCallback<List<UploadInfo>>() { // 上传图片到服务器
                                        @Override
                                        public void onSuccess(List<UploadInfo> uploadInfos) {
                                            String imgId = String.valueOf(localMedia.position);
                                            mView.getRichEditor().removeProgress(imgId); // 移除进度条
                                            mView.getRichEditor().replaceUrl(imgId, uploadInfos.get(0).preview_url); // 将本地uri替换成网络图标url
                                            mView.getProgress().setText(mActivity.getString(R.string.upload_hint, mUploadPosition+1, mUploadFiles.size()));
                                            uploadFile();
                                        }

                                        @Override
                                        public void onLoading(long currentSize, long totalSize, float progress, long networkSpeed) {
                                            super.onLoading(currentSize, totalSize, progress, networkSpeed);
                                            mView.getRichEditor().setProgress(String.valueOf(localMedia.position), (int)(currentSize / totalSize));
                                        }

                                        @Override
                                        public void onError(String strMsg) {
                                            super.onError(strMsg);
                                            ToastUtils.show(mContext, strMsg);
                                        }

                                        @Override
                                        public void onFinish() {
                                            super.onFinish();
                                            mView.hideProgress();
                                        }
                                    });
                                } else {
                                    ToastUtils.show(mContext, mActivity.getString(R.string.picture_too_large));
                                }
                                return;
                            } catch (Exception e) {
                                Logger.e(e.getMessage());
                            }
                        }
                    }

                    mView.hideProgress();
                    ToastUtils.show(mContext, mActivity.getString(R.string.add_picture_fail));
                }

                @Override
                public void onError(Throwable throwable) {
                    mView.hideProgress();
                    Logger.e(throwable.getMessage());
                    ToastUtils.show(mContext, mActivity.getString(R.string.add_picture_fail));
                }
            }).launch();
        }
    }
}
